#include <cstdio>
#include <vector>
#include <iostream>
#include "./src/global.h"
#include "./src/word.h"
#include "./src/syntax.h"
#include "./src/semantic.h"
#include "./src/common.h"

using namespace std;
/**
这些变量都是语法分析和词法分析同时要用到的 
**/ 
using std::vector;

//符号表变量
Table *topTable = NULL;
Type *currType = new Type();		//通过该变量在不同层的语法分析函数间传递值

int main()
{
    const int MAXLEN = 10000;
    remove("./ll1/output/tree.txt");

    char *p_curr, buffer[MAXLEN], temp[MAXLEN];
	int i = 0;
	bool hasWordError = false; 
	WordUnit word;
	vector<WordUnit> words;
	p_curr = buffer;
    FILE * fpr;
    if((fpr = fopen("../input.txt", "r")) == NULL) {
        cout << "can't open this in file";
        exit(0);
    };
    temp[i] = fgetc(fpr);
    while (temp[i] != EOF) {
        temp[++ i] = fgetc(fpr);  
    }
    printf("%s\n", temp);
	preProcess(temp, buffer, i);
	fprintf(stderr, "\n");
	while(*p_curr){				//包含空格及换行符 
		word = lexical(p_curr);
		words.push_back(word);
		if(word.code == -1){
			fprintf(stderr, "[-]WORD ERROR: %s\n", word.value.c_str());
			hasWordError = true;
		}
	}
	if(hasWordError) return 0;	//词法分析 
	
	sym = words.begin();
	program();		//语法分析及符号表建立及语义分析
	
	if(hasIdError) return 0;	//变量错误使用
	freopen("./output/semantic_out.txt", "wt", stdout);		//输出重定向
	i = 0;
	for(vector<QuadTuple>::iterator iter=sequence.begin(); iter!=sequence.end(); iter++){
		fprintf(stdout, "%d ", i++);		//输出序号
		printQuad(*iter);
		fprintf(stdout, "\n");
	}
	fprintf(stderr, "Lextable is printed to ./lex/output\nLL1's first, follow, table and tree are printed to ./ll1/output\nThe output is printed to ./quadList.txt\n");
	return 0;

}
